package com.gimi.cloud.jimi.client.service.moreInfo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.client.service.moreInfo.DebitcardBankcodeService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.mq.service.MqCommonSenderService;
import com.gimi.cloud.jimi.common.utils.DateUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.common.mq.enume.QueueEnum;
import com.gimi.cloud.jimi.dao.dao.User.UserDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.DebitcardBankcodeDao;
import com.gimi.cloud.jimi.dao.dao.moreInfo.MoreInfoDao;
import com.gimi.cloud.jimi.dao.dao.sys.SysConfigDao;
import com.gimi.cloud.jimi.dto.app.moreInfo.DebitcardBankcodeDTO;
import com.gimi.cloud.jimi.dto.app.moreInfo.DebitcardLoginDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoEntity;
import com.gimi.cloud.jimi.entity.user.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @auther loongs
 * @date 2018/1/12  13:30
 */
@Service
public class DebitcardBankcodeServiceImpl implements DebitcardBankcodeService {
    private static final Logger log = LoggerFactory.getLogger(DebitcardBankcodeServiceImpl.class);
    private final static String INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD = "interface_platform_universal_debitCard";
    //最大容错次数暂时定为3次
    private final Integer MAXTIMES = 3;

    private DebitcardBankcodeDao debitcardBankcodeDao;
    private InterfacePlatformRequestService ipRequestService;
    private SysConfigDao sysConfigDao;
    private MoreInfoDao moreInfoDao;
    private MqCommonSenderService commonSenderService;
    private UserDao userDao;
   @Autowired
    public DebitcardBankcodeServiceImpl(DebitcardBankcodeDao debitcardBankcodeDao, InterfacePlatformRequestService ipRequestService,
                                        SysConfigDao sysConfigDao, MoreInfoDao moreInfoDao,MqCommonSenderService commonSenderService,UserDao userDao) {
        this.debitcardBankcodeDao = debitcardBankcodeDao;
        this.ipRequestService = ipRequestService;
        this.sysConfigDao = sysConfigDao;
        this.moreInfoDao = moreInfoDao;
        this.commonSenderService = commonSenderService;
        this.userDao = userDao;
    }


    @Override
    public Response getCreditcardLoginLogin(DebitcardBankcodeDTO debitcardBankcodeDTO) {
       //分两步进行：1、提交基本参数接口；2、查询查询登录状态接口（如果密码不对立即提示）

        log.info("读取配置表并组装请求参数");
        String fengchao_creditCard = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD);
        JSONObject fgJson = JSON.parseObject(fengchao_creditCard);

        Response response = new Response();
        try {

            log.info("============1、提交基本参数接口 开始===============");
            JSONObject subinfo = fgJson.getJSONObject("submit_debit_card_basic_info");

            //拼接arg
            JSONObject argJson = new JSONObject();
            argJson.put("loginType",debitcardBankcodeDTO.getLoginType());
            argJson.put("loginId",debitcardBankcodeDTO.getBankNo());
            argJson.put("password",debitcardBankcodeDTO.getPassword());

            JSONObject subBody = subinfo.getJSONObject("body");
            subBody.put("bankCode", debitcardBankcodeDTO.getFcbcBankCode());
            subBody.put("userCode", debitcardBankcodeDTO.getUserId());
            subBody.put("args",argJson);

            subinfo.put("body", subBody);

            log.info("发起提交基本参数");
            log.info("发起提交基本参数请求json==="+subinfo);
            String subPost = ipRequestService.sendApiPost(subinfo.toJSONString());
            log.info("发起提交基本参数结果json==="+subPost);
            JSONObject subResultJson = JSON.parseObject(subPost);
            JSONObject subResultbody = subResultJson.getJSONObject("body");
            String subResultStatus = subResultbody.getString("status");

            //1：成功; -1：系统错误; 2：参数错误;3：银行行别代码不存在;4：非法请求
            if (!"1".equals(subResultStatus)) {//未成功
                return errStatusForResponse(subResultStatus,response);
            }

            String sessionToken = subResultbody.getString("sessionToken");
            log.info("sessionToken====="+sessionToken);
            if(StringUtil.isBlank(sessionToken)){
                response.setResponseCode(ResponseCodeEnum.ERROR_REQUEST_TOKEN_GET);
                return response;
            }

            log.info("============1、提交基本参数接口 结束===============");

            log.info("============2、查询查询登录状态接口 开始===============");
            JSONObject searchinfo = fgJson.getJSONObject("get_debit_card_login_status");

            JSONObject searchBody = searchinfo.getJSONObject("body");
            searchBody.put("userCode", debitcardBankcodeDTO.getUserId());
            searchBody.put("sessionToken",sessionToken);

            searchinfo.put("body", searchBody);

            log.info("发起查询登录状态参数");
            log.info("============2、查询查询登录状态接口 结束===============");
            return getDebitcardLoginStatus(sessionToken, debitcardBankcodeDTO.getUserId(),searchinfo.toJSONString());


        } catch (Exception e) {
            log.info("基本参数登录异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }

    @Override
    public Response getDebitcardLoginParameter(DebitcardBankcodeDTO debitcardBankcodeDTO) {
        //分两步进行：1、获取基本参数接口 ；2、提交基本参数接口；3、查询查询登录状态接口（如果密码不对立即提示）
        log.info("============1、获取基本参数接口 开始===============");

        log.info("读取配置表并组装请求参数");
        String fengchao_creditCard = sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD);
        JSONObject fgJson = JSON.parseObject(fengchao_creditCard);
        JSONObject paramsinfo = fgJson.getJSONObject("get_debit_card_basic_params");
        JSONObject body = paramsinfo.getJSONObject("body");
        body.put("bankCode", debitcardBankcodeDTO.getFcbcBankCode());
        paramsinfo.put("body", body);
        log.info("获取基本参数的请求json==="+paramsinfo);
        Response response = new Response();
        try {
            log.info("发起获取基本参数");
            String sendApiPost = ipRequestService.sendApiPost(paramsinfo.toJSONString());
            log.info("返回基本参数为==="+sendApiPost);
            JSONObject paResultJson = JSON.parseObject(sendApiPost);
            JSONObject paResultbody = paResultJson.getJSONObject("body");
            String paResultStatus = paResultbody.getString("status");
            //1：成功; -1：系统错误; 2：参数错误;3：银行行别代码不存在;4：非法请求
            if (!"1".equals(paResultStatus)) {//未成功
                return errStatusForResponse(paResultStatus,response);
            }
            log.info("============1、获取基本参数接口 结束===============");
            //成功，将其返回给前端，由前端选择loginType
            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
            response.setRes_data(paResultbody);
            return response;


        }catch (Exception e) {
                log.info("基本参数登录异常" + e.getClass());
                e.printStackTrace();
                response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
                return response;
            }
    }

    public Response errStatusForResponse(String paResultStatus,Response response){
        //1：成功; -1：系统错误; 2：参数错误;3：银行行别代码不存在;4：非法请求
            if ("-1".equals(paResultStatus)) {
                response.setResponseCode(ResponseCodeEnum.NETWORK_ERROR);
                return response;
            }
            if ("2".equals(paResultStatus)) {
                response.setResponseCode(ResponseCodeEnum.PARAMETER_ERROR);
                return response;
            }
            if ("3".equals(paResultStatus)) {
                response.setResponseCode(ResponseCodeEnum.ERROR_MEMORY_CARD);
                return response;
            }
            if ("4".equals(paResultStatus)) {
                response.setResponseCode(ResponseCodeEnum.ERROR_REQUEST);
                return response;
            }
        response.setResponseCode(ResponseCodeEnum.NETWORK_ERROR);
        return response;
    }

    private Response getDebitcardLoginStatus(String sessionToken, Integer userId, String searchJson) throws Exception{
        log.info("获取登录状态");
        String status = null;
        JSONObject glbody = null;
        Response response = new Response();
        String surnameId = "";
        do {
            String glRep = ipRequestService.sendApiPost(searchJson);
            log.info("查询返回json为==="+glRep);
            JSONObject glRepJson = JSON.parseObject(glRep);
            glbody = glRepJson.getJSONObject("body");
            status = glbody.getString("status");
            surnameId = glbody.getString("surnameSid");
        } while ("101".equals(status));

        if (status == null || "-1".equals(status)) {
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }

        DebitcardLoginDTO debitcardLoginDTO = null;
        switch (status) {
            case "000"://信用卡信息抓取并解析成功
            case "201"://正在抓取
            case "200"://抓取成功
            case "100"://登陆成功
                //初始化数据
                initMoreInfo(userId);
                //封装发送到队列里的参数
                debitcardLoginDTO = new DebitcardLoginDTO();
                debitcardLoginDTO.setUserId(userId);
                debitcardLoginDTO.setSessionToken(sessionToken);
                debitcardLoginDTO.setSurnameSid(surnameId);
                commonSenderService.sendMessage2Rabbitmq(QueueEnum.FENGCHAO_DEBITCARD_REPORT, debitcardLoginDTO);
                response.setResponseCode(ResponseCodeEnum.SUCCESSED);
                return response;
            case "001"://需要校验图片验证码
                response.setResponseCode(ResponseCodeEnum.NEED_IMAGECODE_VALIDATION);
                response.setRes_data(glbody);
                return response;
            case "002"://需要校验短信验证码
                response.setResponseCode(ResponseCodeEnum.NEED_PHONECODE_VALIDATION);
                response.setRes_data(glbody);
                return response;
            case "003"://需要校验图片验证码和短信验证码
                response.setResponseCode(ResponseCodeEnum.NEED_VALIDATION);
                response.setRes_data(glbody);
                return response;
            default:
                response.setResponseCode(ResponseCodeEnum.DEBIT_LOGIN_EXCEPTION);
                response.setRes_data(glbody);
                return response;
        }
    }

    /**
     * 初始化数据
     * @param operUserId
     */
    private void initMoreInfo(Integer operUserId){

        User user = userDao.getUserByUserId(operUserId);
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        //查询该用户之前是否有获取过工资卡，需要获取状态为获取中
        MoreInfoEntity moreInfoEntity = moreInfoDao.getMoreInfoByUserIdAndType(operUserId,3);
        //判断是不是新增，true是新增，false已存在
        boolean flag = false;
        if (moreInfoEntity != null && DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 2 ||
                (DateUtil.compare(moreInfoEntity.getReportEffectionEnd(), DateUtil.getNow()) == 0 && !"2".equals(moreInfoEntity.getGetdata()))) {

        }else{
            moreInfoEntity = new MoreInfoEntity();
            moreInfoEntity.setGetdataTime(new Date());
            moreInfoEntity.setAnalysis("0");
            moreInfoEntity.setGetdataErrorTimes(0);

            //user相关
            moreInfoEntity.setAddTime(new Date());
            moreInfoEntity.setAddUname(user.getAddUname());
            moreInfoEntity.setAddUid(user.getUserId());
            moreInfoEntity.setUserId(user.getUserId());

            //3代表工资卡
            moreInfoEntity.setDataType("3");
            moreInfoEntity.setGetdataMaxTimes(MAXTIMES);

            flag = true;
        }
        //获取中
        moreInfoEntity.setGetdata("1");
        if(flag){
            moreInfoDao.insertSelective(moreInfoEntity);
        }else{
            moreInfoEntity.setUpdateUid(user.getUserId());
            moreInfoEntity.setUpdateUname(user.getAddUname());
            moreInfoEntity.setUpdateTime(DateUtil.getNow());
            moreInfoDao.updateByPrimaryKey(moreInfoEntity);
        }

    }

    @Override
    public Response subFengchaoEmailValidCode(DebitcardLoginDTO debitcardLoginDTO) {
        Response response = new Response();
        User user = userDao.getUserByUserId(debitcardLoginDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        String sessionToken = debitcardLoginDTO.getSessionToken();
        Integer userId = debitcardLoginDTO.getUserId();
        log.info("蜂巢工资卡登验证码提交接口开始");
        String debitCard= sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD);
        JSONObject feJson = JSON.parseObject(debitCard);
        JSONObject validcodeJson = feJson.getJSONObject("submit_debit_card_dynamic_params");
        JSONObject body = validcodeJson.getJSONObject("body");

        //拼接arg
        JSONObject argJson = new JSONObject();
        argJson.put(debitcardLoginDTO.getCodeType(),debitcardLoginDTO.getValidCode());

        body.put("args",argJson);
        body.put("sessionToken", sessionToken);
        body.put("userCode", userId+"");

        validcodeJson.put("body", body);
        log.info("蜂巢邮箱登验证码提交接口，拼装参数："+validcodeJson.toJSONString());

        String resStr = null;
        try {
            resStr = ipRequestService.sendApiPost(validcodeJson.toJSONString());
            JSONObject resJson = JSON.parseObject(resStr);
            JSONObject bodyJson = resJson.getJSONObject("body");
            if(bodyJson == null ){
                response.setResponseCode(ResponseCodeEnum.VALIDCODE_DEBITCARD_EXCEPTION);
                return response;
            }
            if(!"1".equals(bodyJson.getString("status"))){
                if("-1".equals(bodyJson.getString("status"))){
                    response.setResponseCode(ResponseCodeEnum.DEBIT_LOGIN_ERROR);
                    return response;
                }else if("-5".equals(bodyJson.getString("status"))){
                    response.setResponseCode(ResponseCodeEnum.DEBIT_LOGIN_SESSIONTOKEN_ERR);
                    return response;
                }else{
                    response.setResponseCode(ResponseCodeEnum.FAILURE);
                    return response;
                }
            }

            //此时再进行一次查询状态，以判断是否验证码登录成功
            JSONObject searchinfo = feJson.getJSONObject("get_debit_card_login_status");

            JSONObject searchBody = searchinfo.getJSONObject("body");
            searchBody.put("userCode", userId);
            searchBody.put("sessionToken",sessionToken);

            searchinfo.put("body", searchBody);

            log.info("发起查询登录状态参数");
            log.info("============3、查询查询登录状态接口 结束===============");
            return getDebitcardLoginStatus(sessionToken, userId,searchinfo.toJSONString());
        } catch (Exception e) {
            log.info("蜂巢邮箱登验证码提交接口异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }

    @Override
    public Response refreshDebitcardValidcode(DebitcardLoginDTO debitcardLoginDTO) {
        Response response = new Response();
        User user = userDao.getUserByUserId(debitcardLoginDTO.getUserId());
        if (user == null) {
            throw new MsgException(ResponseCodeEnum.ERR_USER_INVALID);
        }
        String sessionToken = debitcardLoginDTO.getSessionToken();
        Integer userId = debitcardLoginDTO.getUserId();
        log.info("蜂巢工资卡登验证码刷新接口开始");
        String debitCard= sysConfigDao.getConfigByKey(INTERFACE_PLATFORM_UNIVERSAL_DEBITCARD);
        JSONObject feJson = JSON.parseObject(debitCard);
        JSONObject validcodeJson = feJson.getJSONObject("refresh_debit_card_dynamic_params");
        JSONObject body = validcodeJson.getJSONObject("body");
        //拼接arg
        JSONObject argJson = new JSONObject();
        argJson.put("refreshType",debitcardLoginDTO.getCodeType());

        body.put("args",argJson);
        body.put("sessionToken", sessionToken);
        body.put("userCode", userId);

        validcodeJson.put("body", body);
        log.info("蜂巢邮箱登验证码刷新接口，拼装参数："+validcodeJson.toJSONString());

        String resStr = null;
        try {
            resStr = ipRequestService.sendApiPost(validcodeJson.toJSONString());
            log.info("刷新接口返回结果为==="+resStr);
            if(StringUtil.isBlank(resStr)){
                response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR, "第三方请求异常请再次尝试");
                return response;
            }
            JSONObject resJson = JSON.parseObject(resStr);
            JSONObject bodyJson = resJson.getJSONObject("body");
            if(bodyJson == null ){
                response.setResponseCode(ResponseCodeEnum.REFRESH_DEBITCARD_EXCEPTION);
                return response;
            }

            if (!"001".equals(bodyJson.getString("status")) || !"002".equals(bodyJson.getString("status")) ) {
                response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR, bodyJson.getString("errors"));
                return response;
            }
            response.setRes_data(bodyJson);
            response.setResponseCode(ResponseCodeEnum.SUCCESSED);
            return response;
        } catch (Exception e) {
            log.info("蜂巢邮箱登验证码提交接口异常" + e.getClass());
            e.printStackTrace();
            response.setResponseCode(ResponseCodeEnum.SERVICE_ERROR);
            return response;
        }
    }
}
